package casa.depesos.app.com.frag;

import static android.app.Activity.RESULT_OK;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.support.toast.ToastUtil;

import casa.depesos.app.com.App;
import casa.depesos.app.com.activity.BankCardActivity;
import casa.depesos.app.com.activity.Check2Activity;
import casa.depesos.app.com.activity.MainActivity;
import casa.depesos.app.com.databinding.FragmentGiveFailBinding;
import casa.depesos.app.com.dlg.BaseDialogFragment;
import casa.depesos.app.com.dlg.TimeoutDlg;
import casa.depesos.app.com.http.ReqCallback;
import casa.depesos.app.com.http.bean.GetCodeBean;
import casa.depesos.app.com.http.bean.RepayFailBean;
import casa.depesos.app.com.http.data.BankCard;
import casa.depesos.app.com.http.data.RepayFail;
import casa.depesos.app.com.http.req.ReApplyReq;
import casa.depesos.app.com.http.req.ReloanReq;
import casa.depesos.app.com.http.req.RepayFailReq;
import casa.depesos.app.com.it.Refreshable;
import casa.depesos.app.com.utils.Report;
import casa.depesos.app.com.utils.Utils;

public class GiveFailFragment extends BannerBaseFragment implements Refreshable {

    FragmentGiveFailBinding binding;
    RepayFail info;
    BankCard card;
    boolean change, canChange, timeout = false;

    public GiveFailFragment setParam(boolean canChange) {
        this.canChange = canChange;
        return this;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Report.show("ACTION_SS_008");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentGiveFailBinding.inflate(inflater, container, false);
        binding.rela.setPadding(0, Utils.getStatusBarHeight(App.getApp()), 0, 0);
        binding.frame.frame.setOrientation(LinearLayout.VERTICAL);
        ((ViewGroup.MarginLayoutParams) binding.frame.time.getLayoutParams()).topMargin = Utils.dp2Px(getActivity(), 10);

        if (!canChange) {
            binding.tip.setText("La transacción falló y temporalmente no podemos prestarle dinero. Intente solicitar un préstamo nuevamente después de que termine la cuenta regresiva.");
            binding.linear2.setVisibility(View.GONE);
        }

        showMsg(binding.msg, binding.scroll);
        getName(binding.top);
        getUnRead(binding.top);

        binding.frame.tv.setText("Límite de modificación");

        getData();

        binding.ok.setOnClickListener(v -> {
            check();
        });

        return binding.getRoot();
    }

    private void reApplyTip() {
        new TimeoutDlg().setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
            @Override
            public void onDismiss(boolean isOk, Object value) {
                if (isOk) {
                    showLoading();
                    new ReApplyReq().req(new ReqCallback<GetCodeBean>() {
                        @Override
                        public void callback(boolean success, GetCodeBean bean) {
                            hideLoading();
                            if (success) {
                                Intent i = new Intent(getActivity(), Check2Activity.class);
                                startActivity(i);
                            }
                        }
                    });
                }
            }
        }).show(getChildFragmentManager(), "");
    }

    private void check() {
        if (info == null || card == null) {
            return;
        }
        if (!change) {
            ToastUtil.showLongToast(getActivity(), "Esta tarjeta bancaria tiene problemas y el desembolso falló. Cambie la cuenta de recepción y vuelva a solicitar");
            return;
        }
        Report.click("ACTION_SS_010");
        if (timeout) {
            reApplyTip();
            return;
        }
        showLoading();
        new ReloanReq(info.no, card.id).req(new ReqCallback<GetCodeBean>() {
            @Override
            public void callback(boolean success, GetCodeBean bean) {
                hideLoading();
                if (success) {
                    ((MainActivity) getActivity()).getData();
                }
            }
        });
    }

    private void getData() {
        showLoading();
        new RepayFailReq().req(new ReqCallback<RepayFailBean>() {
            @Override
            public void callback(boolean success, RepayFailBean bean) {
                hideLoading();
                if (success && bean.isValid()) {
                    show(bean.info);
                }
            }
        });
    }

    private void show(RepayFail info) {
        this.info = info;
        card = info.card;
        startCountDown(binding.frame, info.getCountDownTime());
        binding.card.setText(info.card.name + " " + info.card.cardNo);
        binding.linear.setOnClickListener(v -> {
            Report.click("ACTION_SS_009");
            Intent i = new Intent(getActivity(), BankCardActivity.class);
            i.putExtra("from", 1);
            startActivityForResult(i, 11);
        });
    }

    @Override
    protected void countDownTimeout() {
        timeout = true;
        reApplyTip();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 11 && resultCode == RESULT_OK) {
            card = data.getParcelableExtra("card");
            if (card.id.equals(info.card.id)) {
                change = false;
            } else {
                change = true;
            }
            binding.card.setText(card.name + " " + card.cardNo);
        }
    }

    @Override
    public void refresh() {
        getData();
    }
}
